//
//  MCPhotoLibraryDetailViewController.swift
//
//
//  Created by 满聪 on 2019/7/4.
//  Copyright © 2019 CocoaPods. All rights reserved.
//

import UIKit
import Photos

class MCPhotoLibraryDetailViewController: UIViewController {
    // life cycle
    
    public var titleStr: String = ""
    
    public var maxSelected: Int = Int.max
    //照片选择完毕后的回调
    public var completeHandler:((_ assets:[PHAsset])->())?
    //数据源
    public var fetchResult: PHFetchResult<PHAsset> = PHFetchResult<PHAsset>()
    
    /// 是否开始展示遮挡层 (当选中数量 >= 最大可选中数量时候，开启)
    private var isOpenBarrier: Bool = false
    
    //带缓存的图片管理对象
    private var imageManager:PHCachingImageManager!
    
    /// 记录当前选中所有的资源
    private var selectDataArray: [MCPhotoLibraryDetailModel] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        //初始化和重置缓存
        self.imageManager = PHCachingImageManager()
        self.imageManager.stopCachingImagesForAllAssets()
        
        baseSetting()
        
        dealWithData()
        
        initUI()
        
        let indexPath = IndexPath.init(row: dataArray.count - 1, section: 0)
        collectionView.scrollToItem(at: indexPath, at: UICollectionView.ScrollPosition.bottom, animated: false)
    }
    
    
    // MARK: - Setter & Getter
    
    lazy var collectionItemSize = CGSize.init(width: (view.frame.size.width - 3) / 4, height: (view.frame.size.width - 3) / 4)
    
    lazy var collectionView: UICollectionView = {
        
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = collectionItemSize
        layout.sectionInset = .zero
        layout.minimumLineSpacing = 1
        layout.minimumInteritemSpacing = 1
        
        let c = UICollectionView.init(frame: .zero, collectionViewLayout: layout)
        c.backgroundColor = UIColor.white
        c.delegate = self
        c.dataSource = self
        c.register(MCPhotoLibraryDetailCell.self, forCellWithReuseIdentifier: "cell")
        return c
    }()
    
    
    lazy var toolBar: UIToolbar = {
        let bar = UIToolbar()
        return bar
    }()
    
    lazy var completeButton: MCPhotoLibraryCompleteButton = {
        let button = MCPhotoLibraryCompleteButton()
        button.isUserInteractionEnabled = true
        button.center = CGPoint(x: UIScreen.main.bounds.width - 50, y: 22)
        button.isEnabled = false
        button.addTarget(target: self, action: #selector(finishSelectEvent))
        return button
    }()
    
    
    lazy var dataArray: [MCPhotoLibraryDetailModel] = []
}

//MARK: 通知回调，闭包回调，点击事件
extension MCPhotoLibraryDetailViewController {
    @objc func cancelEvent() {
        self.dismiss(animated: true, completion: nil)
    }
    
    //完成按钮点击
    @objc func finishSelectEvent() {
        
        //取出已选择的资源
        var assets:[PHAsset] = []
        
        for model in dataArray {
            if model.isSelected {
                assets.append(model.asset)
            }
        }

        //调用回调函数
        self.navigationController?.dismiss(animated: true, completion: { [weak self] in
            self?.completeHandler?(assets)
        })
    }
    
}


//MARK: 内部方法
extension MCPhotoLibraryDetailViewController {
    
    // 处理数据
    func dealWithData() {
        
        
        for i in 0..<fetchResult.count {
            let model = MCPhotoLibraryDetailModel()
            model.asset = fetchResult[i]
            dataArray.append(model)
        }
        
        collectionView.reloadData()
    }
    
    
    //获取已选择个数
    func getCollectionSelectedCount() -> Int {
        
        var count: Int = 0
        for model in dataArray {
            if model.isSelected {
                count += 1
            }
        }
        return count
    }
    
    // 显示提示框
    func showAlertView(title: String) {
        let alertController = UIAlertController(title: title, message: nil, preferredStyle: .alert)
        
        let cancelAction = UIAlertAction(title:"我知道了", style: .cancel, handler:nil)
        alertController.addAction(cancelAction)
        self.present(alertController, animated: true, completion: nil)
    }
    
    // 修改完成按钮的状态
    func changeCompleteStatus(num: Int)  {
        
        completeButton.num = num
        if num == 0 {
            completeButton.isEnabled = false
        } else {
            completeButton.isEnabled = true
        }
    }
    
   
    
    // 更新选中的标号数字,刷新collectionView
    func collectionViewReloadData() {
        
//        var index = 0
//        for model in dataArray {
//            
//            if model.isSelected {
//                index += 1
//                model.selectIndex = index                
//            } else {
//                model.selectIndex = 0
//            }
//        }
        collectionView.reloadData()
    }
}

//MARK: UI的处理,通知的接收
extension MCPhotoLibraryDetailViewController {
    
    func baseSetting() {
        self.title = titleStr
        view.backgroundColor = UIColor.white
        
        let rightBarItem = UIBarButtonItem(title: "取消", style: .plain, target: self,action:#selector(cancelEvent))
        navigationItem.rightBarButtonItem = rightBarItem
    }
    
    func initUI() {
        
        
        let size = self.view.frame.size
        
        toolBar.frame = CGRect.init(x: 0, y: size.height - 44 - UIDevice.bottomSafeAreaHeight, width: size.width, height: 44)
        view.addSubview(toolBar)

        
        let frame = CGRect.init(x: 0, y: 0, width: size.width, height: size.height - UIDevice.bottomSafeAreaHeight - 44 - 1)
        collectionView.frame = frame
        view.addSubview(collectionView)
        
        let spaceItem = UIBarButtonItem.init(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
        let bar = UIBarButtonItem.init(customView: completeButton)
        toolBar.setItems([spaceItem, bar], animated: true)
    }
}

//MARK: 代理方法
extension MCPhotoLibraryDetailViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataArray.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! MCPhotoLibraryDetailCell
        
        for view in cell.contentView.subviews {
            view.removeFromSuperview()
        }
        
        let model = dataArray[indexPath.row]
        
        cell.row = indexPath.row
        cell.delegate = self
        
        cell.model = model
        
        
        let asset = model.asset
        
        imageManager.requestImage(for: asset, targetSize: collectionItemSize, contentMode: .aspectFill, options: nil) { (image, nil) in
            cell.imageView.image = image
        }
        
        return cell
    }
    
    // 单元格点击响应
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        if let cell = collectionView.cellForItem(at: indexPath)
            as? MCPhotoLibraryDetailCell {
            
            let model = dataArray[indexPath.row]
        
            clickItem(cell, atRow: indexPath, model: model)
        }
    }
}


extension MCPhotoLibraryDetailViewController: MCPhotoLibraryDetailCellDelegate {
    func photoLibraryDetailCell(_ cell: MCPhotoLibraryDetailCell, selectItemAtRow row: Int) {
        
        let model = dataArray[row]
        
        if model.asset.mediaType == .image {
            let title = "你最多只能选择\(self.maxSelected)张照片"
            showAlertView(title: title)
        }
    }
}



extension MCPhotoLibraryDetailViewController {
    
    func clickItem(_ cell: MCPhotoLibraryDetailCell, atRow indexPath: IndexPath, model: MCPhotoLibraryDetailModel) {
        
        let isSelected = model.isSelected
        /// 改变选中状态
        model.isSelected = !isSelected
        
        /// 判断选中的数据是视频还是音频
        var isSelectImage = false
        var isSelectVideo = false

        for item in dataArray {
            
            if item.isSelected {
                let type = item.asset.mediaType

                if type == .image {
                    isSelectImage = true
                }
                if type == .video {
                    isSelectVideo = true
                }
                break
            }
        }

        
        for item in dataArray {
            let type = item.asset.mediaType

            item.isOpenBarrier = false
            if isSelectImage {
                if type == .video {
                    item.isOpenBarrier = true
                }
            }
            
            if isSelectVideo {
                /// 仅可选择一个视频
                if !item.isSelected {
                    item.isOpenBarrier = true
                }
            }
        }

        //获取选中的数量
        let count = getCollectionSelectedCount()
        
        if count == self.maxSelected {
            
            /// 选择数目达到最大数量时，非选中的 置为不可选
            for item in dataArray {
                
                if !item.isSelected {
                    item.isOpenBarrier = true
                }
            }
        } else {
            cell.playAnimate()
            
            //改变完成按钮数字
        }
        changeCompleteStatus(num: count)

        collectionViewReloadData()
    }
}
